package cn.pconline.autoclub.web;

import cn.pconline.autoclub.entity.Club;
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.ClubStyle;
import cn.pconline.autoclub.entity.Style;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.ClubStyleService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.util.AppUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.WebUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * 车友会风格样式Controller
 *
 * @author zhoutianhuai
 */
@Controller
@RequestMapping("/style")
public class ClubStyleController {

    @Autowired
    private ClubStyleService clubStyleService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private UserAuth userAuth;
    @Autowired
    private ClubService clubService;
    private static final Logger log = LoggerFactory.getLogger(ClubStyleController.class);
    /**
     * 替换已经设置的封面图*
     */
    private static final int REPLACE_COVER_YES = 1;
    /**
     * 保留已经设置的封面图*
     */
    private static final int REPLACE_COVER_NO = 0;

    /**
     *
     * 根据车友会ID获得风格样式
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/getClubSytleByClubId.do", method = RequestMethod.GET)
    public void getClubSytleByClubId(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, "callback", "");
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        //clubId为必传参数       
        if (clubId == 0L) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "非法参数clubId！", callback);
            return;
        }
        ClubStyle clubStyle = clubStyleService.getClubStyleByClubId(clubId);
        if (clubStyle == null) {
            printErrorMsg(response, AppUtils.STATUS_FAIL, "暂时还没设置风格样式！", callback);
            return;
        }
        JSONObject json = new JSONObject();
        json.put("clubStyle", clubStyle);
        json.put("code", AppUtils.STATUS_OK);
        printMsg(response, json.toString(), callback);
    }

    private boolean checkPermission(User user, Club club, Style newStyle, HttpServletResponse response) {
        String callback = null;
        //权限判断
        if (user == null || user.getUid() == 0) {
            printErrorMsg(response, AppUtils.STATUS_NOLOGIN_ERROR, "您还没有登陆", callback);
            return false;
        }
        if (club == null) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "参数clubId有误！", callback);
            return false;
        }
        ClubMember m = memberService.findClubMemberByUserId(user.getUid());
        if (m == null || (m.getAdminType() != ClubMember.ADMIN) || m.getClubId() != club.getClubId()) {
            //要当前车友会的会长才有权限
            printErrorMsg(response, AppUtils.STATUS_PERMISSIONS_ERROR, "没有换肤权限", callback);
            return false;
        }
        if (newStyle == null) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "参数styleId有误！", callback);
            return false;
        }
        if (club.getLevelId() < newStyle.getLevel()) {
            printErrorMsg(response, AppUtils.STATUS_PERMISSIONS_ERROR, "车友会等级不够！", callback);
            return false;
        }
        return true;
    }

    /**
     * 保存套装
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/saveSuit.do", method = RequestMethod.POST)
    public void saveSuit(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        long styleId = WebUtils.paramLong(request, "styleId", 0L);
        int keepCover = WebUtils.paramInt(request, "keepCover", REPLACE_COVER_YES);
        User user = userAuth.getUser(request, response);
        Club club = clubService.getClub(clubId);
        Style newStyle = clubStyleService.getStyleByStyleId(styleId);//查询需要设置的套装
        if (!checkPermission(user, club, newStyle, response)) {
            return;
        }
        //查询已经设置的车友会套装
        ClubStyle clubStyle = clubStyleService.getClubStyleByClubId(clubId);
        if (clubStyle == null) {//创建一套全新的套装
            clubStyle = new ClubStyle();
            clubStyle.setClubId(clubId);
            clubStyle.setCreateBy(user.getUid());
           
            JSONObject newJson = JSONObject.parseObject(newStyle.getStyleContent());
            newJson.put(ClubStyle.SHOWIMAGE, "");
            clubStyle.setStyleContent(newJson.toJSONString());
            
            clubStyle.setStyleId(newStyle.getStyleId());
            clubStyle.setType(ClubStyle.TYPE_DEFAULT);
            clubStyle.setUpdateAt(new Date());
            clubStyle.setUpdateBy(user.getUid());
            clubStyleService.createClubStyle(clubStyle);
        } else {//更新旧的套装
            JSONObject newJson = JSONObject.parseObject(newStyle.getStyleContent());
            JSONObject oldJson = JSONObject.parseObject(clubStyle.getStyleContent());
            if (keepCover == REPLACE_COVER_YES) {//不保留原封面图
                newJson.put(ClubStyle.SHOWIMAGE, "");
                newJson.put(ClubStyle.COVERIMAGE, "");

            } else {//保留
                String oldCoverImage = oldJson.getString(ClubStyle.COVERIMAGE);
                //保留自定义时，上传的封面小图片
                String oldZdyCoverImage = oldJson.getString(ClubStyle.SHOWIMAGE);
                newJson.put(ClubStyle.SHOWIMAGE, oldZdyCoverImage);
                newJson.put(ClubStyle.COVERIMAGE, oldCoverImage);
            }

            //最新的车友会styleContent内容
            clubStyle.setStyleContent(newJson.toJSONString());

            clubStyle.setStyleId(newStyle.getStyleId());
            clubStyle.setType(ClubStyle.TYPE_DEFAULT);
            clubStyle.setUpdateAt(new Date());
            clubStyle.setUpdateBy(user.getUid());
            clubStyleService.updateClubStyle(clubStyle);
        }
        printErrorMsg(response, AppUtils.STATUS_OK, "成功更新套装！", null);
    }

    /**
     * 保存封面图
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/saveCoverImage.do", method = RequestMethod.POST)
    public void saveCoverImage(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        long styleId = WebUtils.paramLong(request, "styleId", 0L);
        User user = userAuth.getUser(request, response);
        Club club = clubService.getClub(clubId);
        Style newStyle = clubStyleService.getStyleByStyleId(styleId);//查询需要设置的套装
        if (!checkPermission(user, club, newStyle, response)) {
            return;
        }
        // 查询已经设置的车友会套装
        ClubStyle clubStyle = clubStyleService.getClubStyleByClubId(clubId);
        if (clubStyle == null) {// 创建一套默认的套装
            Style style = clubStyleService.findDefaultStyle();
            clubStyle = new ClubStyle();
            clubStyle.setClubId(clubId);
            clubStyle.setCreateBy(user.getUid());
            clubStyle.setStyleContent(style.getStyleContent());
            clubStyle.setStyleId(style.getStyleId());
            clubStyle.setType(ClubStyle.TYPE_DEFAULT);
            clubStyle.setUpdateAt(new Date());
            clubStyle.setUpdateBy(user.getUid());
            clubStyleService.createClubStyle(clubStyle);
        }

        // 更新旧的套装
        JSONObject newJson = JSONObject.parseObject(newStyle.getStyleContent());
        String newCoverImage = newJson.getString(ClubStyle.COVERIMAGE);
        JSONObject oldJson = JSONObject.parseObject(clubStyle.getStyleContent());
        oldJson.put(ClubStyle.COVERIMAGE, newCoverImage);
        oldJson.put(ClubStyle.SHOWIMAGE, "");//删除自定义时保留的封面小图片
        clubStyle.setStyleContent(oldJson.toJSONString());
        clubStyle.setType(ClubStyle.TYPE_CUSTOM);
        clubStyle.setUpdateAt(new Date());
        clubStyle.setUpdateBy(user.getUid());
        clubStyleService.updateClubStyle(clubStyle);
        printErrorMsg(response, AppUtils.STATUS_OK, "成功更新封面！", null);
    }

    /**
     * 保存自定义样式
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/saveCustomStyle.do", method = RequestMethod.POST)
    public void saveCustomStyle(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        // 获取相关参数
        String callback = null;
        long clubId = WebUtils.paramLong(request, "clubId", 0L);
        long styleId = WebUtils.paramLong(request, "styleId", 0L);
        String coverImage = WebUtils.param(request, "coverImage", "");// 自定义封面大图
        String showImage = WebUtils.param(request, "showImage", "");// 自定义封面缩略图
        //权限判断
        User user = userAuth.getUser(request, response);
        Club club = clubService.getClub(clubId);
        if (user == null || user.getUid() == 0) {
            printErrorMsg(response, AppUtils.STATUS_NOLOGIN_ERROR, "您还没有登陆", callback);
            return;
        }
        if (club == null) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "参数clubId有误！", callback);
            return;
        }
        ClubMember m = memberService.findClubMemberByUserId(user.getUid());
        if (m == null || (m.getAdminType() != ClubMember.ADMIN) || m.getClubId() != club.getClubId()) {
            //要当前车友会的会长才有权限
            printErrorMsg(response, AppUtils.STATUS_PERMISSIONS_ERROR, "没有换肤权限", callback);
            return;
        }
        // customCoverImage、customCss二者必传其一
        if (coverImage.equals("") && styleId == 0) {
            printErrorMsg(response, AppUtils.STATUS_DATA_ERROR, "请至少上传一张封面图或者选一种配色方案", callback);
            return;
        }
        if(!coverImage.equals("")&&club.getLevelId()<3){//三星及三星以上才能自定义封面图
            printErrorMsg(response, AppUtils.STATUS_PERMISSIONS_ERROR, "车友会等级不够！", callback);
            return;
        }
        Style newStyle = null;
        if (styleId > 0) {
            newStyle = clubStyleService.getStyleByStyleId(styleId);// 查询需要设置的样式
            if (coverImage.equals("")) {
                Style s = clubStyleService.findDefaultCoverImage();
                coverImage = s.getCoverString();
            }
            if (club.getLevelId() < newStyle.getLevel()) {
                printErrorMsg(response, AppUtils.STATUS_PERMISSIONS_ERROR, "车友会等级不够！", callback);
                return;
            }
        }
        ClubStyle clubStyle = clubStyleService.getClubStyleByClubId(clubId);
        if (clubStyle == null) {// 创建默认套装
            Style style = clubStyleService.findDefaultStyle();
            clubStyle = new ClubStyle();
            clubStyle.setClubId(clubId);
            clubStyle.setCreateBy(user.getUid());
            clubStyle.setStyleContent(style.getStyleContent());
            clubStyle.setStyleId(style.getStyleId());
            clubStyle.setType(ClubStyle.TYPE_DEFAULT);
            clubStyle.setUpdateAt(new Date());
            clubStyle.setUpdateBy(user.getUid());
            clubStyleService.createClubStyle(clubStyle);
        }
        // 更新旧的套装
        if (newStyle != null) {// 更新样式
            JSONObject oldJson = JSONObject.parseObject(clubStyle.getStyleContent());
            oldJson.put(ClubStyle.CSS, newStyle.getCssString());
            oldJson.put(ClubStyle.BACKGROUND, "");//自定义时去掉背景
            oldJson.put(ClubStyle.FORMCOLOR, newStyle.getFormColor());
            oldJson.put(ClubStyle.LINECOLOR, newStyle.getLineColor());
            oldJson.put(ClubStyle.TXTCOLOR, newStyle.getTxtColor());

            clubStyle.setStyleContent(oldJson.toJSONString());
            clubStyle.setStyleId(newStyle.getStyleId());//更新样式ID，用于显示默认样式

        }
        if (!"".equals(coverImage)) {// 更新封面图
            JSONObject oldJson = JSONObject.parseObject(clubStyle.getStyleContent());
            oldJson.put(ClubStyle.COVERIMAGE, coverImage);
            oldJson.put(ClubStyle.SHOWIMAGE, showImage);
            clubStyle.setStyleContent(oldJson.toJSONString());
        }
        if (!"".equals(coverImage)) {
            clubStyle.setType(ClubStyle.TYPE_CUSTOM);
        } else {
            clubStyle.setType(ClubStyle.TYPE_DEFAULT);
        }
        clubStyle.setUpdateAt(new Date());
        clubStyle.setUpdateBy(user.getUid());
        clubStyleService.updateClubStyle(clubStyle);
        printSuccessMsg(response, "保存成功", null, callback);
    }

    private void printMsg(HttpServletResponse resp, String str, String callback) {
        callback = EncodeUtils.encodeForHTMLFilterNull(callback);
        try {
            java.io.PrintWriter w = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                w.print(callback + "(" + str + ")");
            } else {
                w.print(str);
            }
            w.flush();
            w.close();
        } catch (IOException ex) {
            log.error("response输出出错了", ex);
        }
    }

    private void printSuccessMsg(HttpServletResponse resp, String msg, JSONObject data, String callback) {
        JSONObject json = new JSONObject();
        json.put("code", AppUtils.STATUS_OK);
        if (StringUtils.isNotEmpty(msg)) {
            json.put("message", msg);
        }
        if (data != null) {
            json.put("data", data);
        }
        printMsg(resp, json.toJSONString(), callback);
    }

    private void printErrorMsg(HttpServletResponse resp, int code, String msg, String callback) {
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("message", msg);
        printMsg(resp, json.toJSONString(), callback);
    }
}
